$(function(){
	 
	getCurentdate(function(str){
		$("#time_inline").datetimePicker({
	        title: '请选择日期',
	        cssClass:'datetimestyless', 
	        times: function () {
		          return [];
		        },
	        min: "2016-01-01",
	        max: str,	       
	        onChange: function (picker, values, displayValues) {
	          console.log(values);
	          $("#time_inline").val(str);
	        }
	    });
		
	})
	
	//搜索成员	
	var timer=null;
	$('#loacation').on('input',function(){	
		$("#loacation").removeAttr('weaid');
		if($(".search_wrapper ul").children().length==0&&$('.search_wrapper .weui-loadmore').length==0){			
			$('.search_wrapper ul').after('<div class="weui-loadmore"><i class="weui-loading"></i><span class="weui-loadmore__tips">正在加载</span></div>');
		}
		if($(".search_group").is(":hidden")){
			$(".search_group").slideDown(200);
		}
		clearTimeout(timer);
		 timer=setTimeout(function(){	
			var str=$("#loacation").val();
			if(str.length>1){
				var last_str="";
				if(str.indexOf('•')==-1){
					last_str=str;
				}else{
					var arr=str.split('•');
					for(var i=0; i<arr.length; i++){
						if(i==(arr.length-1)){
							last_str=last_str+$.trim(arr[i]);
						}else{
							last_str=last_str+$.trim(arr[i])+'|';
						}						
					}
				}
				
				get_city(last_str,'',function(data){
					if(data.length>0){
						var item=data[0];
						var city_str=item.area_2!=''?' • '+item.area_2:'';
						var text=item.area_1+city_str;
						if(text!=''){
							$("#loacation").val(text);
						}	
						$("#loacation").attr("weaid",item.weaid);
					}
				});
			}
						
		},1000)
		
	});	
	
	//在搜索板处点击获取地址
	$(document).on('click','.search_wrapper ul li',function(){		
		$("#loacation").attr('weaid',$(this).attr('weaid'));
		$("#loacation").val($(this).text());
		$(".search_group").slideUp(200);
	})
	
	//定位
	$(document).on('click','.locationbtn',function(){
		if(!$(this).hasClass("disabled")){
			$(this).addClass("disabled")
			getCurrentPosition();
			$("#loacation").removeAttr("weaid").val('');
			if($(".search_group").is(":hidden")){
				$(".search_group").slideDown(200);
				
			}
			if($('.search_wrapper .weui-loadmore').length==0){
				$('.search_wrapper ul').empty();
				$('.search_wrapper ul').after('<div class="weui-loadmore"><i class="weui-loading"></i><span class="weui-loadmore__tips">正在加载</span></div>');
			
			}
		}
		
	})
	 
	
	
	//确定选择的天气和日期
	$(".save_weather").on("click",function(){
		$(this).attr("disabled",true);
		var weaid=$("#loacation").attr('weaid');
		var date=$("#time_inline").val();
		if((weaid!=undefined&&weaid!='')&&(date!=undefined&&date!='')){
			weatherObj.date=date;			
			weatherObj.location=$("#loacation").val();
			weatherObj.weaid=weaid;
			if(weaid==0){
				//修改当前 一图一记的天气信息  
				weatherObj.wea='';			
				weatherObj.icon='';
 				changeweather()
				$.closePopup("#weather_mask");
				$("#loacation,#time_inline").val('');
				$("#loacation").removeAttr("weaid");
				$("#loacation").removeAttr("disabled");
			}else{
				history_weather(weaid,date);
				
			}			
			
		}else{			
			$.alert('无法识别该城市，请重新输入', "提示", function() {
				$("#loacation").removeAttr("disabled");				
			})
		}
		
		
	})
		
	
	
	
})

function getcityweaid(){
	
	
}


function getCurentdate(fn){
	 var time=new Date; 
	 var year = time.getFullYear();
	var month = time.getMonth() + 1;
	var day = time.getDate(); 	
	var str= year + "-" + (month<10?'0'+month:month)+ "-" + (day<10?'0'+day:day);

	fn(str);
}



 var weatherObj=new Object;  //存储当前一图一记 选择 的天气数据
//获取城市   
function get_city(locationstr,coordinate,fn){
	if($('.search_wrapper .weui-loadmore').length==0){
		$('.search_wrapper ul').after('<div class="weui-loadmore"><i class="weui-loading"></i><span class="weui-loadmore__tips">正在加载</span></div>');
	}
	if($(".search_group").is(":hidden")){
		$(".search_group").slideDown(200);
	}
	$.ajax({ 
			  		
		url:baseUrl+'other/tianqi/get_city',
		type:'GET',
		data:{coordinate:coordinate,location:locationstr},
		dataType:"json",
        success:function(data){
        	if(data.code!=200){				
				$(".weather_error").html('提示信息：'+data.description);
				 $('.search_wrapper .weui-loadmore').remove();
			}else{
				$(".search_wrapper ul").empty();	
				for(var i=0; i<data.data.length; i++){
					var item=data.data[i];
					//var htm='<li weaid="'+item.weaid+'">'+item.area_1+' '+item.area_2+' '+item.area_3+'</li>';
					var city_str=item.area_2!=''?' • '+item.area_2:'';
					var htm='<li weaid="'+item.weaid+'">'+item.area_1+city_str+'</li>';
					$(".search_wrapper ul").append(htm);
				}
				$(".search_wrapper .weui-loadmore").remove();
				if($(".search_wrapper li").length==0){
					$(".search_wrapper ul").append('<div class="search_not_txt">暂无数据</div>');						
					//$(".search_group").slideUp(200);
				}
				fn(data.data);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			 $('.search_wrapper .weui-loadmore').remove();
				if(XMLHttpRequest.status==0){
					 $(".weather_error").html('提示信息：加载失败，请重新加载');
				}else{					
					$.alert(XMLHttpRequest.status, "提示");
					$(".weather_error").html('提示信息：'+XMLHttpRequest.status);
				}
				
				
							
		}
    });
	
	
}
   
 //获取城市 历史天气
function history_weather(weaid,date){
	$.ajax({ 			  		
		url:baseUrl+'other/tianqi/get_history_weather',
		type:'GET',
		data:{weaid:weaid,date:date},
		dataType:"json",
        success:function(data){
	//$.getJSON(baseUrl+'other/tianqi/get_history_weather?weaid='+weaid+'&date='+date,function(data){
			if(data.code!=200){				
				$.alert(data.description, "提示");
			}else{				
				if(weaid!=0){
					var item=data.data;		
					//weatherObj.location=weatherObj.location+' • '+item.weather+'  '+item.temperature;
					weatherObj.wea=item.weather+'  '+item.temperature;			
					weatherObj.icon=item.weather_icon;//'http://img1-qcloud.hucai.com//2017/12/12/201712121128467914.jpg?imageMogr2/thumbnail/300x300';//item.weather_icon,					
						
					 if(!UtilProperty.weathericon.hasOwnProperty(weatherObj.icon)){	
						 	var imga = new Image();
						 	imga.crossOrigin = "anonymous";
						 	imga.id=weatherObj.icon;
							imga.onload=function(){	
								UtilProperty.weathericon[weatherObj.icon] = imga;
								//修改当前 一图一记的天气信息  
			 					changeweather()
								$.closePopup("#weather_mask");
								$("#loacation,#time_inline").val('');
								$("#loacation").removeAttr("weaid");
							}
							imga.src=item.weather_icon;//'http://img1-qcloud.hucai.com//2017/12/12/201712121128467914.jpg?imageMogr2/thumbnail/300x300'; //item.weather_icon;
						}else{			
							//修改当前 一图一记的天气信息  
			 				changeweather()
							$.closePopup("#weather_mask");
							$("#loacation,#time_inline").val('');
							$("#loacation").removeAttr("weaid");
						}
					}else{
						//修改当前 一图一记的天气信息  
						weatherObj.wea='';			
						weatherObj.icon='';
			 			changeweather()
						$.closePopup("#weather_mask");
						$("#loacation,#time_inline").val('');
						$("#loacation").removeAttr("weaid");
					}
			}
			
			if($("#loacation").attr("disabled")!=undefined){
				$("#loacation").removeAttr("disabled");
			}
	},
	error: function(XMLHttpRequest, textStatus, errorThrown){			
			$.alert('加载失败，请重新加载', "提示");	
			if($("#loacation").attr("disabled")!=undefined){
				$("#loacation").removeAttr("disabled");
			}				
		}
    });
}  
   
   
 //修改当前 一图一记的天气信息  
function changeweather(){
  	if(opentype == 2) {
		if(UtilProperty[work_id] != undefined && UtilProperty[work_id].worker[0].control_list.length == 0) {
			//打开空的作品页 选择的布局
			Emptyworklayout();
		} else {
			if(ismodel == 7) { //lym 于2017 12.11 新增一图一记修改 判断					
				$("#originaleditor,#pagemain").hide().empty();
				$('.lay_type_item').removeClass("editoring");
				$('.lay_type_item[layout_categoryid="' + ismodel + '"]').addClass("editoring");
				//遍历布局列表
				lay_list(ismodel);
				$(".layout_type").hide();
				$(".layout_list_box").show();
				$("#half .stop-editor").hide();
				$("#half").append('<div class="popup_forbidden _fixed"></div>')
				$("#half").popup();
				//显示竖版横版
				showlayout_sty();
				opentype = 2;
				$(".worker_con").hide();
				$(".originalwork").show();
	
			} else {
				//新建作品  根据选择的模板出现相应的布局					
				showgetlayout();
			}
		}
	} else { //更换日历模板
		var currentid = $(".save_weather").attr("currentid");
		if(currentid == undefined) { //lym 2017 11.20 新增月历修改						
			var tempmodel = $(".layout_type .editoring").attr('layout_categoryid');
			//遍历布局列表		
			lay_list(tempmodel);
			$(".layout_type ").hide();
			$(".layout_list_box").show();
			$("#half").popup();
			//显示竖版横版
			showlayout_sty()
		} else {// 修改一图一记的天气信息
			comfrimWeatherToCanvas();
		}
	}
	
	  	
  }
   
   
   

//一图一记  天气数据的生成
function weatherdata(ctxt,w_id,element,scale){
	var datalist = new Object;	
	var list= element.element_list[0];	
	var sty=JSON.parse(list.style);
	var pic,pic_width=0,pic_height=0;
	if(list.content.icon!=''){
		if(UtilProperty.weathericon.hasOwnProperty(list.content.icon)){
			pic=UtilProperty.weathericon[list.content.icon];
			pic_width=pic.width;
			pic_height=pic.height;
		}
	}
	
	var _x=50;
	var _transform=sty.direction*90;
	var text_width,text_x,text_height;
	
	if(_transform==90||_transform==270){
		text_width=element.height-pic_height-_x;
	 	text_x=pic_height+_x;
		text_height=element.width/2;
		
	}else{
		text_width=element.width-pic_width-_x;
	 	text_x=pic_width+_x;
		text_height=element.height/2;
	}
	if(pic){
	datalist.icon={
		imgurl:list.content.icon,
		img: pic,
		image_id: list.content.icon,
		x: 0,
		y: 0,
		w: pic.width * scale,
		h: pic.height * scale,
		imgx: 0,
		imgy: 0,
		imgw: 0,
		imgh: 0,
		imgoldx: 0,
		imgoldy: 0,
		imgoldw: pic.width,
		imgoldh: pic.height,
		transform: 0,	
	}
	}
	
	datalist.date=new Object;
	datalist.location=new Object; 
	var fontsize = parseInt(Number(sty.size) * scale);
	if(fontsize < 12) {
		var newscale = 12 / fontsize;
		datalist.date = {
			x: parseInt(text_x * scale * newscale),
			y: parseInt(text_height * scale * newscale)*0.1,
			width: parseInt(text_width * scale * newscale),
			height: parseInt(text_height * scale * newscale),
			family: version!="undefined"?version_family:'Microsoft YaHei',
			size: 12 + "px",
			weight: '',
			color: sty.color.toString(),
			style: '',
			center: sty.align != '' ? sty.align.toString() : "center",
			lineHeight: parseInt((Number(sty.size) * Number(sty.line_space)) * scale * newscale),
			text: list.content.date,
			transform: 0,
			newscale: newscale,
			ischange: false
		}
		datalist.location = {
			x: parseInt(text_x * scale * newscale),
			y: parseInt(text_height * scale * newscale)*1.1,
			width: parseInt(text_width * scale * newscale),
			height: parseInt(text_height * scale * newscale),
			family: version!="undefined"?version_family:'Microsoft YaHei',
			size: 12 + "px",
			weight: '',
			color: sty.color.toString(),
			style: '',
			center: sty.align != '' ? sty.align.toString() : "center",
			lineHeight: parseInt((Number(sty.size) * Number(sty.line_space)) * scale * newscale),
			text: list.content.location+'  '+list.content.wea,
			transform: 0,
			newscale: newscale,
			ischange: false
		}
	
	} else {
		datalist.date = {
			x: parseInt(text_x * scale),
			y: parseInt(text_height * scale)*0.1,
			width: parseInt(text_width * scale),
			height: parseInt(text_height * scale),
			family: version!="undefined"?version_family:'Microsoft YaHei',
			size: parseInt(Number(sty.size) * scale) + "px",
			weight: '',
			color: sty.color.toString(),
			style: '',
			center: sty.align != '' ? sty.align.toString() : "center",
			lineHeight: parseInt((Number(sty.size) * Number(sty.line_space)) * scale),
			text: list.content.date,
			transform: 0,
			newscale: 1,
			ischange: false
		}
		datalist.location = {
			x: parseInt(text_x * scale),
			y: parseInt(text_height * scale)*1.1,
			width: parseInt(text_width * scale),
			height: parseInt(text_height * scale),
			family: version!="undefined"?version_family:'Microsoft YaHei',
			size: parseInt(Number(sty.size) * scale) + "px",
			weight: '',
			color: sty.color.toString(),
			style: '',
			center: sty.align != '' ? sty.align.toString() : "center",
			lineHeight: parseInt((Number(sty.size) * Number(sty.line_space)) * scale),
			text: list.content.location+'  '+list.content.wea,
			transform: 0,
			newscale: 1,
			ischange: false
		}
	}
	
	
	/*if(datalist.date.transform == 90 || datalist.date.transform == 270) {
		var w = datalist.date.height;
		var h = datalist.date.width;
		datalist.date.width = w;
		datalist.date.height = h;
		datalist.location.width = w;
		datalist.location.height = h;
	}*/
		
	weatherTocanvas(ctxt,w_id,element,scale,datalist,_transform)
		
}


//一图一记  天气数据转成canvas
function weatherTocanvas(ctxt,w_id,element,scale,datalist,_transform){
	var canvas=document.createElement('canvas');
	var context = canvas.getContext('2d');	
	if(_transform==90||_transform==270){
		canvas.width=element.height*scale;
		canvas.height=element.width*scale;
	}else{
		canvas.width=element.width*scale;
		canvas.height=element.height*scale;
	}
	
		
	
	for(var i in datalist){
		if(i=='icon'){
			if(datalist[i].transform>0) {		
				originalcanvasimgrote(context,datalist[i])
			}else{ 							
				drawImgByStatus(context,datalist[i]);	
			}
		}else if(i=='date'||i=='location'){			
			drawlinetext(datalist[i], function(result, strenter, data) {
				//context.drawImage(data, datalist[i].x , datalist[i].y, datalist[i].width, datalist[i].height);
				//context.rect(datalist[i].x , datalist[i].y, datalist[i].width, datalist[i].height);
				context.drawImage(data, datalist[i].x/datalist[i].newscale , datalist[i].y/datalist[i].newscale, datalist[i].width/datalist[i].newscale, datalist[i].height/datalist[i].newscale);
				//context.rect(datalist[i].x/datalist[i].newscale , datalist[i].y/datalist[i].newscale, datalist[i].width/datalist[i].newscale, datalist[i].height/datalist[i].newscale);
				context.closePath();
				context.save();					
				context.restore();
	
			});
		}
	}
	
	//if(_transform!=0) {
		//textRoate(canvas,canvas.width,canvas.height,ctxt,_transform,element.coordinate_x*scale,element.coordinate_y*scale,1);
		
		var _elementlist = {
			imgurl: '',
			img: canvas,
			image_id: '',
			x: element.coordinate_x * scale,
			y: element.coordinate_y * scale,
			w: element.width * scale,
			h: element.height * scale,
			imgx: element.coordinate_x * scale,
			imgy: element.coordinate_y * scale,
			imgw: 0,
			imgh: 0,
			imgoldx: 0,
			imgoldy: 0,
			imgoldw: canvas.width,
			imgoldh: canvas.height,
			transform: _transform,
		}
		if(_transform > 0) {
			originalcanvasimgrote(ctxt, _elementlist)
		} else {
			drawImgByStatus(ctxt, _elementlist);
		}
		
	/*}else{
		ctxt.drawImage(canvas,element.coordinate_x*scale,element.coordinate_y*scale,element.width*scale, element.height*scale);
							
	}
	ctxt.rect(element.coordinate_x*scale, element.coordinate_y*scale, element.width*scale, element.height*scale);
	ctxt.closePath();
	ctxt.save();
	ctxt.clip();	
	ctxt.restore();	*/
}


//把修改  一图一记  的天气数据修改后     重新绘制到canvas
 function comfrimWeatherToCanvas(){	
 		var k=$(".save_weather").attr("currentid"); 		
		var index= $("#originalcanvas").attr("page");
		var canvasData=UtilProperty[work_id].worker[index].control_list;		
		for(var i=0; i<canvasData.length;i++){			
				if(k==canvasData[i].id){
					var element=canvasData[i];
					if(element.element_list.length>0){						
						UtilProperty[work_id].worker[index].control_list[i].element_list[0].content={date:weatherObj.date,icon:weatherObj.icon,location:weatherObj.location,weaid:weatherObj.weaid,wea:weatherObj.wea};
						UtilProperty[work_id].worker[index].control_list[i].ischange=true;
					}
				}
			
		
		}
		$(".save_weather").removeAttr("currentid");
		weatherObj ={};	
		changeoriginalcanvas(index);		
		changepagemainbox(index);
 }

//打开当前 天气选择
function weatherpopup(date,text,weaid){	
	$("#time_inline").val(date);
	$("#time_inline").picker("setValue", [date.split('-')[0], date.split('-')[1], date.split('-')[2]]);
	if(text!=''){
		$("#loacation").val(text);
	}
	if(weaid!=''){
		$("#loacation").attr("weaid",weaid);	
	}
	
	if($(".search_group").is(":hidden")){
		$(".search_group").slideUp(200);
	}
	$("#weather_mask").popup();
}

//新建时初始化 天气的选择
function create_weather(){
	$("#loadtoast").show();
	getCurrentPosition();	
}


//判断是否含有月历模板
function judeweather(index){	
	var item=UtilProperty[work_id].worker[index];
	var isflag=false;
	for(var k=0; k<item.control_list.length;k++){
		var list=item.control_list[k];
		if(list.control_id==4){
			isflag=true;	
			var item_a=list.element_list[0].content;
			weatherObj={date:item_a.date,icon:item_a.icon,location:item_a.location,weaid:item_a.weaid,wea:item_a.wea};			
			return isflag;
		}
		
	}
	
	return isflag;
}

